package com.baozun.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie工具类
 * 
 * @Title:
 * @Company:宝尊电子商务有限公司
 * @Description:
 * @Author:xiaozhou.zhou
 * @Since:2015年1月8日
 * @Copyright:Copyright (c) 2014
 * @ModifyDate:
 * @Version:1.1.0
 */
public class CookieUtil {
    
    /**
     * 获取cookieMap
     * 
     * @param request
     * @return
     * @Description:
     */
    public static Map<String, Cookie> getCookieMap(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
    
    // 新增cookie
    public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue, int maxAge) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    
    /**
     * 根据cookie名称清除cookie
     * 
     * @param request
     * @param cookieName
     * @Description:
     */
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                deleteCookie(response, cookie);
                break;
            }
        }
    }
    
    /**
     * 删除cookie
     * 
     * @param cookie
     * @Description:
     */
    public static void deleteCookie(HttpServletResponse response, Cookie cookie) {
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
    
    /**
     * 通过cookie名称获取cookie
     * 
     * @param name
     * @return
     * @Description:
     */
    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        Cookie result = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                result = cookie;
                break;
            }
        }
        return result;
    }
}
